﻿Public Class Form1
    Dim PythonPath As String
    Dim PythonInstalled As Boolean = False
    Dim NeedsSaving As Boolean = False
    Dim DeltaH As Integer
    Dim DeltaW As Integer

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SetTabStops(editArea)
        labelFile.Text = ""
        labelPosition.Text = ""
        Dim currpath As String = CType(My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Environment", "Path", ""), String)

        currpath = currpath.ToLower
        ' Check to see if Python is installed
        If System.IO.File.Exists("C:\Python25\python.exe") Then
            PythonPath = "c:\python25\"
        ElseIf System.IO.File.Exists("C:\Python26\python.exe") Then
            PythonPath = "c:\python26\"
        Else
            MsgBox("It does not appear that you have Python installed in C:\Python25\ or C:\Python26" + _
                   " - please download and install from www.python.org and then run this program.  " + _
                   " PythonLearn suggests Python 2.5.4 even though it is not the most current version of Python.")
            End
        End If
        If currpath.Contains(PythonPath) Then
            ' MsgBox("You have a sweet path" + currpath)
        Else
            Dim result = MsgBox("Before this program will work, it must add Python to your command line path.", MsgBoxStyle.OkCancel, _
                        "Updating Command Line Environment...")
            If result = MsgBoxResult.Cancel Then
                MsgBox("This program cannot function unless it adds Python to the command line path.", MsgBoxStyle.OkOnly, _
                       "For help see www.pythonlearn.com.")
                End
            End If
            currpath = currpath.Trim
            Debug.Print("Old Path=" + currpath)
            If currpath.Length < 1 Then
                currpath = PythonPath
            Else
                If Not currpath.EndsWith(";") Then
                    currpath = currpath + ";"
                End If
                currpath = currpath + PythonPath
            End If
            Debug.Print("New Path=" + currpath)
            MsgBox("Setting your path to: " + currpath)
            MsgBox("You must log out of Windows and log back in for this setting to take effect and for the program to fully function.")
            My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Environment", "Path", currpath)
        End If
        UpdateEnabled()
    End Sub

    Private Sub Form1_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize
        DoResize()
    End Sub

    Private Sub DoResize()
        DeltaH = 108 ' Me.Size.Height - editArea.Size.Height
        DeltaW = 28 ' Me.Size.Width - editArea.Size.Width
        Dim X As Size = New Size(Me.Size.Width - DeltaW, Me.Size.Height - DeltaH)
        editArea.Size = X
    End Sub

    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
          (ByVal handle As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByRef lParam As Integer) As Integer


    Private Sub SetTabStops(ByVal ctlTextBox As TextBox)

        Const EM_SETTABSTOPS As Integer = &HCBS

        ' Set tab stops at character position 4, 8, and 12
        Dim tabs() As Integer = {16, 32, 48, 64, 80, 96, 112, 128, 144}

        SendMessage(ctlTextBox.Handle, EM_SETTABSTOPS, tabs.Length, tabs(0))

    End Sub

    Private Sub UpdateEnabled()
        ' We have an open file
        Dim haveFile As Boolean = (labelFile.Text.Length > 0)
        Dim haveText As Boolean = (editArea.Text.Length > 0)
        ' Save As
        bSaveAs.Enabled = haveText
        ' Save
        bSave.Enabled = haveFile And haveText And NeedsSaving
        'Execute
        bExecute.Enabled = haveFile And haveText
        If NeedsSaving Then
            bExecute.Text = "Save and Execute"
        Else
            bExecute.Text = "Execute"
        End If
    End Sub

    Private Sub Execute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bCommand.Click
        ' Set an environment variable.
        System.Environment.SetEnvironmentVariable("PYTHONLEARN", "YES")

        System.Environment.CurrentDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
        Shell("cmd.exe", AppWinStyle.NormalFocus)
    End Sub


    Private Sub DoOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bOpen.Click
        Dim fdlg As OpenFileDialog = New OpenFileDialog()
        fdlg.Title = "C# Corner Open File Dialog"
        fdlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)

        fdlg.Filter = "All files (*.*)|*.*|Python files (*.py)|*.py"
        fdlg.FilterIndex = 2
        fdlg.RestoreDirectory = True
        If fdlg.ShowDialog() = DialogResult.OK Then
            labelFile.Text = fdlg.FileName
            Dim fileReader As System.IO.StreamReader
            fileReader = My.Computer.FileSystem.OpenTextFileReader(fdlg.FileName)
            Dim stringReader As String
            Dim expanded As String
            Dim lines() As String
            Dim count As Integer = 0
            stringReader = fileReader.ReadLine()
            While stringReader <> Nothing
                ' MsgBox(stringReader)
                expanded = ExpandTabs(stringReader)
                ReDim Preserve lines(0 To count)
                lines(count) = expanded
                count = count + 1
                stringReader = fileReader.ReadLine()
            End While
            fileReader.Close()
            editArea.Lines = lines
            labelPosition.Text = ""
            NeedsSaving = False
        End If
        UpdateEnabled()
    End Sub

    Private Function ExpandTabs(ByVal inputstring As String) As String
        If inputstring.Length < 1 Then
            Return inputstring
        End If
        Dim thischars As Char() = inputstring.ToCharArray
        Dim thosechars() As Char
        Dim j As Integer = 0
        Dim changed As Boolean
        changed = False
        For i = 0 To thischars.Length - 1
            ReDim Preserve thosechars(0 To j)
            If thischars(i) = vbTab Then
                thosechars(j) = " "
                For k = 1 To 3 - (i Mod 4)
                    j = j + 1
                    ReDim Preserve thosechars(0 To j)
                    thosechars(j) = " "
                    changed = True
                Next
            Else
                thosechars(j) = thischars(i)
            End If
            j = j + 1
        Next
        If Not changed Then
            Return inputstring
        End If

        '  Return the altered string
        Dim retval As String
        retval = thosechars
        Return retval
    End Function

    Private Sub editArea_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles editArea.TextChanged
        ' Debug.Print("YO")
        NeedsSaving = True
        UpdateEnabled()
    End Sub

    Private Sub editArea_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles editArea.KeyUp
        Dim selst = Me.editArea.SelectionStart
        Dim whichline As Integer = Me.editArea.GetLineFromCharIndex(Me.editArea.SelectionStart)
        Dim whichchar As Integer = (selst - Me.editArea.GetFirstCharIndexOfCurrentLine) + 1
        labelPosition.Text = "Line " + (whichline + 1).ToString + ",  Char " + whichchar.ToString
        ' Debug.Print(e.KeyCode)
        If e.KeyCode <> Keys.Tab Then
            Return
        End If

        If Me.editArea.Text.Length < 1 Then
            Return
        End If

        ' Process the current line and expand tabs
        Dim thisline As String = Me.editArea.Lines(whichline)
        Dim newstring = ExpandTabs(thisline)
        If newstring = thisline Then
            Return
        End If

        Dim thelines As String() = Me.editArea.Lines
        thelines(whichline) = newstring
        Me.editArea.Lines = thelines
        Me.editArea.SelectionStart = selst + newstring.Length - thisline.Length

        ' Also Update Row/Column
        selst = Me.editArea.SelectionStart
        whichline = Me.editArea.GetLineFromCharIndex(selst)
        whichchar = (selst - Me.editArea.GetFirstCharIndexOfCurrentLine) + 1
        labelPosition.Text = "Line " + (whichline + 1).ToString + ",  Char " + whichchar.ToString
    End Sub

    Private Sub Terminal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bExecute.Click
        If labelFile.Text.Length < 1 Then
            MsgBox("No File Name Found - Cannot Save")
            Return
        ElseIf NeedsSaving Then
            If Not DoSave(labelFile.Text) Then
                Return
            End If
        End If

        Dim parentPath As String = My.Computer.FileSystem.GetParentPath(labelFile.Text)

        System.Environment.CurrentDirectory = parentPath
        UpdateEnabled()
        Shell(PythonPath + "python.exe -i """ + labelFile.Text + """", AppWinStyle.NormalFocus)
    End Sub

    Private Sub DoSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bSave.Click
        If labelFile.Text.Length < 1 Then
            MsgBox("No File Name Found - Cannot Save")
        Else
            DoSave(labelFile.Text)
        End If
        UpdateEnabled()
    End Sub

    Private Sub DoNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bNew.Click
        editArea.Text = ""
        labelFile.Text = ""
        labelPosition.Text = ""
        UpdateEnabled()
    End Sub

    Private Function DoSave(ByVal FileName As String) As Boolean
        Try
            Dim ourText As String = editArea.Text
            My.Computer.FileSystem.WriteAllText(FileName, ourText, False, System.Text.Encoding.ASCII)
            NeedsSaving = False
            labelFile.Text = FileName
            labelPosition.Text = ""
            Return True
        Catch es As Exception
            MessageBox.Show(es.Message)
            Return False
        End Try
    End Function

    Private Sub SaveAs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bSaveAs.Click
        Try
            Dim fdlg As SaveFileDialog = New SaveFileDialog()
            fdlg.Title = "C# Corner Open File Dialog"
            fdlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
            fdlg.Filter = "All files (*.*)|*.*|Python files (*.py)|*.py"
            fdlg.FilterIndex = 2
            fdlg.RestoreDirectory = True

            If fdlg.ShowDialog() = DialogResult.OK Then
                DoSave(fdlg.FileName)
            End If
        Catch es As Exception
            MessageBox.Show(es.Message)
        End Try
        UpdateEnabled()
    End Sub

    Private Sub bHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bHelp.Click
        System.Diagnostics.Process.Start("http://www.pythonlearn.com")
    End Sub

    Private Sub bAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bAbout.Click
        Dim AboutBox1 As New AboutBox1
        AboutBox1.Show()
    End Sub

End Class
